package atdd.kata.matchers;

import atdd.kata.core.domain.Person;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;

import java.sql.ResultSet;
import java.sql.SQLException;

public class PersonMatcher<T> extends BaseMatcher<T> {

    private ApplicationContext applicationContext;

    public PersonMatcher(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public boolean matches(Object arg) {
        Person expectedPerson = (Person)arg;
        JdbcTemplate jdbcTemplate = new JdbcTemplate(applicationContext.getBean(DataSource.class));
        Person actualPerson = jdbcTemplate.queryForObject("select * from Person where first_name='"
                +expectedPerson.getFirstName()+"'", new RowMapper<Person>() {
            @Override
            public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new Person(
                        rs.getString("first_name"),
                        rs.getString("last_name"),
                        rs.getString("middle_name"),
                        rs.getString("job_title"));
            }
        });
        return actualPerson.toString().equals(expectedPerson.toString());
    }

    public void describeTo(Description description) {
        description.appendText("incorrectly persisted");
    }

    @Factory
    public static <T> Matcher<T> isPersistedIn(ApplicationContext applicationContext) {
        return new PersonMatcher<T>(applicationContext);
    }



}